package com.shihc.spring.transaction.service.impl;

import com.shihc.spring.transaction.dao.UserDao;
import com.shihc.spring.transaction.model.User;
import com.shihc.spring.transaction.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by shihc on 2016/1/21.
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserDao userDao;

    @Transactional
    @Override
    public User saveUser(User user) {
        user = userDao.save(user);
        deleteUser(null);
        return user;
    }

    //@Transactional(readOnly = true)//不会有任何错误产生
    @Transactional
    @Override
    public int deleteUser(User user) {
        if(user == null){
            throw new IllegalArgumentException("参数无效");
        }
        userDao.delete(user);

        for(int i=0; i<5; i++){
            User tmp = new User();
            tmp.setName("test");
            tmp.setEmail("test@tt.com");
            saveUser(tmp);
            if(i == 2){
                throw new IllegalArgumentException("业务处理异常");
            }
        }
        return 1;
    }

    @Transactional
    @Override
    public int deleteUser2(User user) {
        if(user == null){
            throw new IllegalArgumentException("参数无效");
        }

        //打印两条sql
        //Hibernate: select user0_.id as id1_0_0_, user0_.email as email2_0_0_, user0_.name as name3_0_0_ from users user0_ where user0_.id=?
        //Hibernate: delete from users where id=?
        //解释：这里涉及到JPA的缓存机制。更新删除的时候JPA都需要先维护缓存才可以删除。
        // 如果你要直接删除，必须写EQL语句，和SQL差不都，不过那样有可能造成整个对象所有缓存失效。
        userDao.deleteUser(user.getId());
        return 1;
    }
}
